﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using RestSharp;

namespace HealthCardService.Common
{
    public class genericCallInterface
    {
        /// <summary>
        /// 通用请求接口数据
        /// </summary>
        public static JObject CallInterface(string BASE_URL, string API_PATH, IDictionary<string, Object> req)
        {
            // 1.构造通用参数commonIn。
            commonInHelper commonIn = new commonInHelper();

            // 2.使用入参req,签名commonIn。
            commonIn.CommonInSign(req);

            // 3.构造请求参数,获取返回信息。封装后返回。
            IDictionary<string, Object> postPara = new Dictionary<string, Object>
            {
                { "commonIn", commonIn.CommonIn },
                { "req", req }
            };

            //开始请求
            //构建客户端对象
            var _result = postRestResult(BASE_URL, API_PATH, postPara);

            /*
             *
             *
             * 此处应该加入返回值解析，判断请求返回状态，并对_result重新封装后返回。
             *
             *
             */

            return _result;

        }

        /// <summary>
        /// 通过RestSharp请求接口数据
        /// </summary>
        private static JObject postRestResult(string BASE_URL, string API_PATH, IDictionary<string, Object> postPara)
        {
            //构建客户端对象
            RestClient client = new RestClient(BASE_URL);
            //构建请求
            RestRequest request = new RestRequest(API_PATH, Method.POST);
            request.AddJsonBody(postPara);
            //设置请求头部参数
            request.AddHeader("contentType", "application/json");

            return JObject.Parse(client.Execute(request).Content);
        }
    }
}
